from django.forms import model_to_dict
from django.shortcuts import render

from elasticsearch import Elasticsearch

from .form import SearchForm
from .models import Information
import concurrent.futures as cf

import requests


def download_image(bv):
    r = requests.get("https://api.bilibili.com/x/web-interface/view", {"bvid": bv})
    if r.status_code == 200:
        return bv, r.json()["data"]["pic"]
    else:
        return bv, 404


# Create your views here.
def search(request):
    context = {}
    if request.method == 'GET':
        form = SearchForm()
        context['form'] = form
    elif request.method == 'POST':
        form = SearchForm(request.POST)
        if form.is_valid():
            with Elasticsearch() as es:
                res = es.search(index="bilibilivedio", query={"match": {"fulltext": form.cleaned_data["query"]}})
                context['result'] = {i["_source"]['bv']: i["_source"] for i in res["hits"]["hits"]}
            with cf.ThreadPoolExecutor(max_workers=4) as executor:
                future_to_urls = [executor.submit(download_image, bv) for bv in context['result']]
                for future in cf.as_completed(future_to_urls):
                    bv, url = future.result()
                    context['result'][bv]['pic'] = url
            context['result'] = context['result'].values()
            context['form'] = form
    return render(request, "retrieval.html", context)


def detail(request, bv):
    context = {}
    if request.method == 'GET':
        context["inform"] = model_to_dict(Information.objects.get(bv=bv))
    return render(request, "detail.html", context)
